package com.x.service.transactional;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.x.dao.UserDAO;
import com.x.model.Role;
import com.x.model.User;

@Component("myUserDetailsService")
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private UserDAO userDAO;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = userDAO.getUserByName(username);
		List<Role> roles = user.getRoles();
		List<GrantedAuthority> roleList = new ArrayList<GrantedAuthority>();
		for (Role role : roles) {
			roleList.add(new SimpleGrantedAuthority(role.getRole()));
		}
		return new org.springframework.security.core.userdetails.User(
				user.getUsername(), user.getPassword(), true, true, true, true,
				roleList);
	}
}
